package com.bwc.aidemo.chatting

import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bwc.aidemo.R
import com.bwc.aidemo.util.MMKVUtil
import com.tencent.mmkv.MMKV

class ChattingAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    private companion object {
        const val TYPE_BOT = 0
        const val TYPE_USER = 1
    }

    private val messages = mutableListOf<Message>()

    // 机器人消息ViewHolder
    class BotViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val tvMessage: TextView = itemView.findViewById(R.id.ai_chatting_input)
    }

    // 用户消息ViewHolder
    class UserViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val tvMessage: TextView = itemView.findViewById(R.id.user_chatting_input)
    }

    override fun getItemViewType(position: Int): Int {
        return if (messages[position].isUser) TYPE_USER else TYPE_BOT
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val inflater = LayoutInflater.from(parent.context)
        return when (viewType) {
            TYPE_USER -> {
                val view = inflater.inflate(R.layout.item_chatting_user, parent, false)
                UserViewHolder(view)
            }
            TYPE_BOT -> {
                val view = inflater.inflate(R.layout.item_chattinf_ai, parent, false)
                BotViewHolder(view)
            }
            else -> throw IllegalArgumentException("Unknown view type: $viewType")
        }
    }

    override fun getItemCount(): Int = messages.size

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val message = messages[position]
        when (holder) {
            is UserViewHolder -> holder.tvMessage.text = message.content
            is BotViewHolder -> holder.tvMessage.text = message.content
        }
    }

    fun addMessage(message: Message) {
        messages.add(message)
        notifyItemInserted(messages.size - 1)
    }

    fun updateMessage(position: Int,newString: String){
        Log.d("updateMessage", "updateMessage: $newString")
        val newStrings = newString.replace("+++","AI生成中")
        splitAndSave(newString)

        if (position in messages.indices){
            messages[position].content = newStrings
            notifyItemChanged(position)
        }
    }


   private fun splitAndSave(text: String) {
        // 使用 "+++" 作为分隔符来分割文本
        val splitText = text.split("+++")
            .map { it.trim() }  // 去除前后的空格
            .filter { it.isNotEmpty() } // 只保留非空的内容

        // 调用保存方法将分割后的文本保存到文件
        if (splitText.isNotEmpty()) {
            Log.d("TAG", "splitAndSave: $splitText")
            MMKVUtil.put("wenben",splitText)
        } else {
            println("没有有效内容需要保存！")
        }
    }
}
